package com.lyx.bookmanager.controller;

import com.lyx.bookmanager.mapper.ReaderMapper;
import com.lyx.bookmanager.mapper.UserMapper;
import com.lyx.bookmanager.pojo.Book;
import com.lyx.bookmanager.pojo.Reader;
import com.lyx.bookmanager.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    ReaderMapper readerMapper;

    @RequestMapping({"/", "/index"})
    public String login(HttpSession session) {
        return "index";
    }

    @RequestMapping({"/toLoginPage"})
    public String toLoginPage() {
        return "login";
    }


    @RequestMapping(value = "/toRegisterPage")
    public String toRegisterPage() {
        return "register";
    }

    @RequestMapping("register")
    public String register(@RequestParam("username") String username, @RequestParam("password") String password,
                           @Param("telcode") String telcode, @Param("name") String name, Model model, HttpSession session) {
        if (username == null || password == null || telcode == null || name == null) {
            model.addAttribute("flag", 0);
            model.addAttribute("msg", "注册失败");
            return "user/register_tips";
        }
        if (userMapper.insert(username, password, "user")) {
            Reader reader = new Reader();
            reader.setReaderId(Long.parseLong(username));
            reader.setTelcode(telcode);
            reader.setName(name);
            readerMapper.insert(reader);
            model.addAttribute("flag", 1);
            model.addAttribute("msg", "注册成功");

        } else {
            model.addAttribute("flag", 0);
            model.addAttribute("msg", "注册失败");
        }

        return "user/register_tips";
    }

//
////    @RequestMapping(value = "/register", method = RequestMethod.POST)
////    public String register(@RequestParam("username") String username, @RequestParam("password") String password) {
////
////        userMapper.insert(username, password, "user");
////        return "login";
////    }
}
